package com.yunxi.service.bom.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.bom.CatalogVO;
import com.yunxi.eai.pojo.bom.PackageConstraintBomVO;
import com.yunxi.eai.pojo.esb.EsbVO;
import com.yunxi.eai.pojo.bom.ModelVO;
import com.yunxi.eai.pojo.bom.PackageVO;
import com.yunxi.eai.service.bom.BOMService;
import com.yunxi.hubToBaseData.pojo.VehicleConfigReqVO;
import com.yunxi.hubToBaseData.pojo.VehiclePackageReqVO;
import com.yunxi.hubToBaseData.service.BaseDataSaveService;
import com.yunxi.hubToBiz.pojo.PackageConstraintVO;
import com.yunxi.hubToBiz.service.ConstraintConfigDubboService;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.hubToBaseData.pojo.VehicleSpectrumReqVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/5/21.
 */
@Service
@Qualifier("bomServiceImpl")
public class BOMServiceImpl implements BOMService {
    protected static final Logger LOGGER = LoggerFactory.getLogger(BOMServiceImpl.class);

   /* @Reference(version = "${demo.service.version}",
            application = "${dubbo.application.id}",
            registry = "${dubbo.registry.address}",
            check = false,
            timeout = 10000
    )*/
    @Autowired
    BaseDataSaveService baseDataSaveServiceByBub;
    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    @Autowired
    private ConstraintConfigDubboService constraintConfigDubboServiceImpl;
    @Override
    public ApiResult distributeBom(EsbVO esbVO) {
        String serviceName = esbVO.getServiceName();
        String reqBody = esbVO.getReqBody();
        ApiResult apiResult=null;
        if (serviceName.equals(Constant.BOM_MODEL)) {
            //型谱
            apiResult=saveVehicleSpectrum(esbVO);
        } else if (serviceName.equals(Constant.BOM_CATALOG)) {
            //工程配置
            apiResult=saveVehicleConfig(esbVO);
        } else if (serviceName.equals(Constant.BOM_PACKAGE)) {
            //选装包
            apiResult=saveVehiclePackage(esbVO);
        }else if (serviceName.equals(Constant.BOM_CONSTRAINT)) {
            //选装包约束
            apiResult=saveVehiclePackageConstraint(esbVO);
        } else {
            return ResponseUtil.fail(500,"没有对应的业务接口!");
        }
        return apiResult;
    }

    /**
     * 选装包约束
     * @param esbVO
     * @return
     */
    private ApiResult saveVehiclePackageConstraint(EsbVO esbVO) {
        ApiResult apiResult=null;
        String reqBody = esbVO.getReqBody();
        ArrayList<PackageConstraintBomVO> packageConstraintList = JSON.parseObject(reqBody, new TypeReference<ArrayList<PackageConstraintBomVO>>() {});
        String packageConstraint = JSONObject.toJSONString(packageConstraintList);
        EaiLog eaiLog=new EaiLog();
        eaiLog.setEsbEaiContent(packageConstraint);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送约束规则给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            List<PackageConstraintVO> dataList=new ArrayList<>();
            for (int i = 0; i < packageConstraintList.size(); i++) {
                PackageConstraintBomVO packageConstraintBomVO =  packageConstraintList.get(i);
                PackageConstraintVO packageConstraintVO=new PackageConstraintVO();
                BeanUtils.copyProperties(packageConstraintBomVO,packageConstraint);
                dataList.add(packageConstraintVO);
            }
            apiResult =  constraintConfigDubboServiceImpl.receiveBomData(dataList);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(21888,"["+esbVO.getServiceName()+"]");
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21999,"["+esbVO.getServiceName()+"]");
            eaiLog.setDisposeStatus(2);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21666,"["+esbVO.getServiceName()+"]");
        }
        return apiResult;
    }

    //选装包
    private ApiResult saveVehiclePackage(EsbVO esbVO) {
        ApiResult apiResult=null;
        String reqBody = esbVO.getReqBody();
        ArrayList<PackageVO> packageList = JSON.parseObject(reqBody, new TypeReference<ArrayList<PackageVO>>() {});
        ArrayList<VehiclePackageReqVO> packageReList=new ArrayList<>();
        for (int i = 0; i < packageList.size(); i++) {
            PackageVO packageVO =  packageList.get(i);
            VehiclePackageReqVO vehiclePackageReqVO=new VehiclePackageReqVO();
            BeanUtils.copyProperties(packageVO,vehiclePackageReqVO);
            packageReList.add(vehiclePackageReqVO);
        }
        String packageRe = JSONObject.toJSONString(packageReList);
        EaiLog eaiLog=new EaiLog();
        eaiLog.setEsbEaiContent(packageRe);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送选装包给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            apiResult = baseDataSaveServiceByBub.saveVehiclePackage(packageReList);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(21888,"["+esbVO.getServiceName()+"]");
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21999,"["+esbVO.getServiceName()+"]");
            eaiLog.setDisposeStatus(2);
        }
      //  Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
           // SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21666,"["+esbVO.getServiceName()+"]");
        }
        return apiResult;
    }
    //工程配置
    private ApiResult saveVehicleConfig(EsbVO esbVO) {
        ApiResult apiResult=null;
        String reqBody = esbVO.getReqBody();
        ArrayList<CatalogVO> catalogList = JSON.parseObject(reqBody, new TypeReference<ArrayList<CatalogVO>>() {});
        ArrayList<VehicleConfigReqVO> configList=new ArrayList<>();
        for (int i = 0; i < catalogList.size(); i++) {
            CatalogVO catalogVO=catalogList.get(i);
            VehicleConfigReqVO vehicleConfigReqVO = new VehicleConfigReqVO();
            BeanUtils.copyProperties(catalogVO,vehicleConfigReqVO);
            configList.add(vehicleConfigReqVO);
        }
        // System.out.println(catalogList);
       // apiResult= baseDataSaveService.saveVehicleConfig(configList);
        String congig = JSONObject.toJSONString(configList);
        EaiLog eaiLog=new EaiLog();
        eaiLog.setEsbEaiContent(congig);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送工程配置给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            apiResult= baseDataSaveServiceByBub.saveVehicleConfig(configList);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(21888,"["+esbVO.getServiceName()+"]");
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21999,"["+esbVO.getServiceName()+"]");
            eaiLog.setDisposeStatus(2);
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
          //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21666,"["+esbVO.getServiceName()+"]");
        }
        return apiResult;
    }
    //车型
    private ApiResult saveVehicleSpectrum(EsbVO esbVO) {
        ApiResult apiResult=null;
        String reqBody = esbVO.getReqBody();
        ArrayList<ModelVO> modelList = JSON.parseObject(reqBody, new TypeReference<ArrayList<ModelVO>>() {});
        ArrayList<VehicleSpectrumReqVO> spectrumlList=new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            VehicleSpectrumReqVO vehicleSpectrumReqVO=new VehicleSpectrumReqVO();
            ModelVO modelVO =  modelList.get(i);
            BeanUtils.copyProperties(modelVO,vehicleSpectrumReqVO);
            spectrumlList.add(vehicleSpectrumReqVO);
        }
        //apiResult=baseDataSaveService.saveVehicleSpectrum(spectrumlList);
        String spectrum = JSONObject.toJSONString(spectrumlList);
        EaiLog eaiLog=new EaiLog();
        eaiLog.setEsbEaiContent(spectrum);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送车辆型谱给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            apiResult=baseDataSaveServiceByBub.saveVehicleSpectrum(spectrumlList);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(21888,"["+esbVO.getServiceName()+"]");
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21999,"["+esbVO.getServiceName()+"]");
            eaiLog.setDisposeStatus(2);
        }
      //  Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
        //    SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(21666,"["+esbVO.getServiceName()+"]");
        }
        return apiResult;
    }
}
